package com.edou.member.controller.weChat;

import com.edou.base.controller.BaseController;
import com.edou.base.util.EncryptUtil;
import com.edou.member.entity.MemberUser;
import com.edou.member.form.MemberUserForm;
import com.edou.member.service.IMemberUserService;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.text.SimpleDateFormat;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author zhangyaofang
 * @create 2018-11-27 10:55 AM
 * @desc 微信小程序登录
 **/
@Controller("memberUserLoginWechatController")
@Scope("prototype")
@RequestMapping("/wechat/member")
public class MemberUserLoginWechatController extends BaseController {

	@Autowired
	private IMemberUserService memberUserService;


	/**
	 * 小程序登录
	 */
	@RequestMapping(value = "/login.htm", method = RequestMethod.POST)
	public ModelAndView login(@RequestBody MemberUserForm model){
		try{
			JSONObject msg = new JSONObject();
//            // 手机号非空验证
			if(null == model.getMobile() || "".equals(model.getMobile().trim())){
				msg.put("001","手机号不能为空!");
				return ajaxJSON(Status.error,"false",msg);
			}
			// 密码非空验证
			if(null == model.getPassword() || "".equals(model.getPassword().trim())){
				msg.put("002","密码不能为空!");
				return ajaxJSON(Status.error,"false",msg);
			}
//            // 密码转码
			String passwordEncrypt = EncryptUtil.encryptionPw(model.getPassword());
			MemberUser memberUser = memberUserService.getMemberUserByAccountAndPassword(model.getMobile(),passwordEncrypt);
			if(null == memberUser){
				return ajaxJSON(Status.error,"手机号和密码输入有误!");
			}

			if(null == memberUser){
				return ajaxJSON(Status.error,"手机号和密码输入有误!");
			}
			LinkedHashMap<String,Object> map = new LinkedHashMap<>();
			map.put("id",memberUser.getId());
			map.put("name",memberUser.getName());
			map.put("nickName", memberUser.getNickName());
			map.put("mobile",memberUser.getMobile());
			map.put("city",memberUser.getAddress());
			msg.put("memberUser",map);

			return ajaxJSON(Status.success,"true",msg);
		} catch (java.lang.Exception e) {
			logger.info("用户登录 发生错误"+e.getMessage(),e);
			return ajaxJSON(Status.error, e.getMessage());
		}
	}
}